package com.etcn.common.utils;

import java.io.File;
import java.util.Date;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import ch.qos.logback.classic.Logger;

@Component
public class UploadImageHandler {

	/**
	 * 业务处理 logger
	 */
	private Logger serviceLogger = (Logger) LoggerFactory.getLogger("service_file_log");

	@Value("${image.upload.path}")
	private String imageUploadPath;

	@Value("${image.down.url}")
	private String imageDownUrl;

	public String uploadFile(MultipartFile file, String subDir, String fileName) {
		if (StringUtil.isEmpty(fileName)) {
			fileName = DataUtil.createUniqueNum(new Date().toString()) + ".jpg";
		} else {
			fileName += ".jpg";
		}
		new File(imageUploadPath + File.separator + subDir).mkdirs();
		String filePath = imageUploadPath + File.separator + subDir + File.separator + fileName;
		try {
			file.transferTo(new File(filePath));
		} catch (Exception e) {
			e.printStackTrace();
		}
		String imgUrl = imageDownUrl + "/" + subDir + "/" + fileName;
		serviceLogger.info("上传文件地址 : " + imgUrl);
		return imgUrl;
	}

}
